package com.cmwa.scbp.business.customerEquity.navinfo.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.stereotype.Service;

import com.cmwa.scbp.business.customerEquity.navinfo.dao.CmwaProductMarketLaunchDao;
import com.cmwa.scbp.business.customerEquity.navinfo.dao.NavInfoDao;
import com.cmwa.scbp.business.customerEquity.navinfo.entity.CmwaProductMarketLaunchVo;
import com.cmwa.scbp.business.customerEquity.navinfo.entity.NavInfoBaseVo;
import com.cmwa.scbp.business.customerEquity.navinfo.service.NavInfoService;
import com.cmwa.scbp.base.mvc.entity.Page;
import com.cmwa.scbp.base.mvc.entity.SearchParam;
import com.cmwa.scbp.utils.DateUtils;
import com.cmwa.scbp.utils.Echarts;
import com.cmwa.scbp.utils.SQLUtil;
import com.cmwa.scbp.utils.Series;
import com.cmwa.scbp.utils.SessionUtils;


/**
 * 客户权益核算-净值-逻辑
 * @author ex-lihui
 *
 */
@Service
public class NavInfoServiceImpl implements NavInfoService{
	
	private static final Log logger = LogFactory.getLog(NavInfoServiceImpl.class);
	
	@Resource
	private NavInfoDao navInfoDao;
	
	@Resource
	private CmwaProductMarketLaunchDao cmwaProductMarketLaunchDao;

	/**
	 * 查询列表
	 */
	@Override
	public Page<NavInfoBaseVo> queryNavListPage(SearchParam sp) {
		List<NavInfoBaseVo> navResultList = navInfoDao.queryNavListPage(batchCondition(sp));
		return Page.create(navResultList, sp.getStart(), sp.getLimit(), sp.getTotal());
	}

	
	/**
	 * 拼接传入参数
	 * @param sp
	 * @return
	 */
	public SearchParam batchCondition(SearchParam sp) {
		if (StringUtils.equals(SessionUtils.getEmployee().getEmpType(), "OUT")) {
			sp.getSp().put("empId", SessionUtils.getEmployee().getID());
		}
		String subPrdCode = String.valueOf(sp.getSp().get("subPrdCode")) ;
		if(StringUtils.isNotBlank(subPrdCode) && subPrdCode.contains(",")){
			String[] val = subPrdCode.split(",");
			String inSql = SQLUtil.buildOracleSQLIn(Arrays.asList(val), 1000, "T.SUB_PRD_CODE");
			sp.getSp().put("subPrdCode", inSql);
		}
		return sp;
	}
	
	
	@Override
	public NavInfoBaseVo queryNavDataById(String navBizId) {
		return navInfoDao.queryNavDataById(navBizId);
	}


	@Override
	public void updateNavValuesById(NavInfoBaseVo navInfoBaseVo) {
		navInfoBaseVo.setModifyId(SessionUtils.getEmployee().getID());
		navInfoDao.updateNavValuesById(navInfoBaseVo);
	}
	
	
	/**
	 * 折线数据主方法
	 */
	@Override
	public Echarts queryNavInfoBySolid(HttpServletResponse response, SearchParam sp) {
		
		Set<String> setName = new HashSet<String>();	//存放产品名称
		Set<String> setDate = new HashSet<String>();	//存放日期
		
		List<NavInfoBaseVo> navResultList = navInfoDao.queryNavList(batchCondition(sp));
		List<NavInfoBaseVo> newList = collectionSortData(navResultList);
		List<NavInfoBaseVo> compareList = new ArrayList<NavInfoBaseVo>(newList);
		
		for(NavInfoBaseVo vo : newList) {
			setName.add(vo.getFundSname());
			setDate.add(vo.getAssessmentDate().toString());
		}
		//图例：产品
		List<String> legend = new ArrayList<String>(setName);
		 
		//横坐标:日期
		List<String> axis = new ArrayList<String>(setDate);
		Collections.sort(axis);
		
        //纵坐标的值（每个时间段对应的量）
		List<Series> series = new ArrayList<Series>();
	 	for(String prdName : setName) {
	 		
	 		List<BigDecimal>  nav = new ArrayList<BigDecimal>();
	 		for(String date : axis) {
	 			
	 			String values = "";
				Iterator<NavInfoBaseVo> itor = compareList.iterator();
				while(itor.hasNext()) {
					NavInfoBaseVo compareVo = (NavInfoBaseVo) itor.next();
					
					//TODO 使用产品编码匹配
					if(StringUtils.equals(prdName, compareVo.getFundSname()) && StringUtils.equals(date, String.valueOf(compareVo.getAssessmentDate()))){
						values = compareVo.getNav(); 
						itor.remove();
					}
				}
				if(StringUtils.isNotBlank(values)) {
					nav.add(new BigDecimal(values));
				}else {
					nav.add(null);
				}
				
			}
			series.add(new Series(prdName,"line",nav));
		}
         Echarts echarts = new Echarts(legend, axis, series);
         return echarts;
	}
	
	
	/**
	 * 数据处理
	 * @param navResultList
	 * @return
	 */
	public List<NavInfoBaseVo> collectionSortData(List<NavInfoBaseVo> navResultList){
		Collections.sort(navResultList);
		Set<NavInfoBaseVo> navSet = new HashSet<NavInfoBaseVo>(navResultList);
		List<NavInfoBaseVo> newNavtList = new ArrayList<NavInfoBaseVo>(navSet);
		Collections.sort(newNavtList);
		return newNavtList;
	}
	
	
	
	
	/**
	 * 净值接口文件导出
	 */
	@SuppressWarnings({ "deprecation", "resource" })
	@Override
	public void exportNavDetail(HttpServletResponse response,SearchParam sp) {
		
		   ServletOutputStream output = null;
		   List<NavInfoBaseVo> navResultList = null;
			
		   try {
				navResultList = navInfoDao.queryNavList(batchCondition(sp));
				output = response.getOutputStream();
				String fileName = new String("净值".getBytes("GB2312"), "ISO8859-1");
				response.setContentType("application/octet-stream ");  
				response.setHeader("Content-Disposition", "Attachment;filename="+ fileName + ".xls");
		   } catch (IOException e1) {
				logger.error("查询净值数据错误",e1);
		   }
		   
	       HSSFWorkbook wb = new HSSFWorkbook();
	       
	       HSSFCellStyle titleStyle = wb.createCellStyle();
	       titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
	       HSSFFont titleFont = wb.createFont(); // 创建字体
	       titleFont.setFontName("宋体"); // 黑体
	       titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 加粗
	       titleStyle.setFont(titleFont);
	       HSSFSheet sheet1 = wb.createSheet("净值导出");
	       sheet1.setColumnWidth(0, 20 * 256);
	       sheet1.setColumnWidth(1, 20 * 256);
	       sheet1.setColumnWidth(2, 20 * 256);
	       sheet1.setColumnWidth(3, 20 * 256);
	       
	       HSSFRow row1 = sheet1.createRow(0);
	       String[] titleRow1 = new String[] {"产品名称", "净值日期","净值"};
	       for (int i = 0; i < titleRow1.length; i++) {
	           HSSFCell cell = row1.createCell(i, Cell.CELL_TYPE_STRING);
	           cell.setCellValue(titleRow1[i]);
	           cell.setCellStyle(titleStyle);
	       }
	       HSSFCellStyle titleStyle1 = wb.createCellStyle();
	       titleStyle1.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中
	       HSSFFont titleFont1 = wb.createFont(); // 创建字体
	       titleFont1.setFontName("宋体"); // 黑体
	       titleStyle1.setFont(titleFont1);
	       
	       if(CollectionUtils.isNotEmpty(navResultList)){
	           for (int i = 0; i < navResultList.size(); i++) {
	        	   NavInfoBaseVo dto = navResultList.get(i);
	              HSSFRow rowData = sheet1.createRow(i + 1);
	              HSSFCell cell = null;
	              cell = rowData.createCell(0, Cell.CELL_TYPE_STRING);
	              cell.setCellValue(dto.getFundSname());			//产品名称
	              cell.setCellStyle(titleStyle1);
	              
	              cell = rowData.createCell(1, Cell.CELL_TYPE_STRING);
	              cell.setCellValue(dto.getNavDate());		//估值日期
	              cell.setCellStyle(titleStyle1);
	              
	              cell = rowData.createCell(2, Cell.CELL_TYPE_STRING);
	              cell.setCellValue(dto.getNav());					//净值
	              cell.setCellStyle(titleStyle1);
	            
	           }
	       }
	       try {
	    	   wb.write(output);
	    	   output.flush();
	       } catch (IOException e) {
	    	   logger.error("关闭流错误",e);
	       }finally {
	    	   try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	       }
	     
	}


	@Override
	public void exportNavInterfaceFile(String theDate, String faCode, HttpServletResponse response) {
		String bizDate = DateUtils.formatDate(DateUtils.parseDate(theDate, DateUtils.DATE_FORMAT_yMd_EN), DateUtils.DATE_FORMAT_yMd_EN2);
		String fileName = "AP_NAV_" + bizDate + "_01";
		response.setContentType("application/x-download");// 设置response内容的类型
		response.setHeader("Content-disposition", "attachment;filename=" + fileName);// 设置头部信息
		
		
		OutputStream outputStream = null;
		FileInputStream fileInputStream = null;
		try {
			// 创建净值文件
			File navFile = createNavFile(theDate, faCode, null);
			
			outputStream = response.getOutputStream();
			
			fileInputStream = new FileInputStream(navFile);
			
			byte[] b = new byte[fileInputStream.available()];
			fileInputStream.read(b);
			outputStream.write(b);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fileInputStream.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * 创建净值文件
	 * @param theDate 日期
	 * @param faCode 基金代码（与系列产品编号二选一参数）
	 * @param prjCodes 系列产品编号（与基金代码二选一参数）
	 */
	@Override
	public File createNavFile(String theDate, String faCode, String prjCodes) {
		String bizDate = DateUtils.formatDate(DateUtils.parseDate(theDate, DateUtils.DATE_FORMAT_yMd_EN), DateUtils.DATE_FORMAT_yMd_EN2);
		
		File tempFile = null;
		BufferedWriter bufferedWriter = null;
		FileWriter fileWriter = null;
		try {
			List<CmwaProductMarketLaunchVo> queryNavList = cmwaProductMarketLaunchDao.queryNavList(faCode, theDate, prjCodes);
			
			tempFile = File.createTempFile(UUID.randomUUID().toString(), "");
			fileWriter = new FileWriter(tempFile);
			
			bufferedWriter = new BufferedWriter(fileWriter);
			
			bufferedWriter.write("BTATOGZDAT");
			bufferedWriter.write("\n");
			bufferedWriter.write("29");
			bufferedWriter.write("\n");
			bufferedWriter.write(bizDate);
			bufferedWriter.write("\n");
			bufferedWriter.write(String.valueOf(queryNavList.size()));
			bufferedWriter.write("\n");
			
			if (CollectionUtils.isNotEmpty(queryNavList)) {
				// 逐行写入数据
				byte[] spaByte = { 0x01, 0x01 };
				String spa = new String(spaByte);
				for (int i = 0; i < queryNavList.size(); i++) {
					CmwaProductMarketLaunchVo cmwaProductMarketLaunchVo = queryNavList.get(i);
					StringBuffer sb = new StringBuffer();
					sb.append(i + 1);
					sb.append(spa); // 分隔符： ASCII 控制字符 SOH
					sb.append(DateUtils.formatDate(cmwaProductMarketLaunchVo.getTheDate(), DateUtils.DATE_FORMAT_yMd_EN2));
					sb.append(spa);
					sb.append(cmwaProductMarketLaunchVo.getBatchNum()== null ? "0":cmwaProductMarketLaunchVo.getBatchNum());
					sb.append(spa);
					sb.append(cmwaProductMarketLaunchVo.getFaCode()== null ?"":cmwaProductMarketLaunchVo.getFaCode());
					sb.append(spa);
					sb.append(StringUtils.stripToEmpty(cmwaProductMarketLaunchVo.getPrdType()));
					sb.append(spa);
					sb.append(cmwaProductMarketLaunchVo.getNetValue() == null ? "0" : cmwaProductMarketLaunchVo.getNetValue());
					sb.append(spa);
					sb.append(cmwaProductMarketLaunchVo.getAccNetValue() == null ? "0" : cmwaProductMarketLaunchVo.getAccNetValue());
					sb.append(spa);
					sb.append(cmwaProductMarketLaunchVo.getRateReturn() == null ? "0" : cmwaProductMarketLaunchVo.getRateReturn());
					sb.append(spa);
					sb.append(cmwaProductMarketLaunchVo.getAccRateReturn() == null ? "0" : cmwaProductMarketLaunchVo.getAccRateReturn());
					sb.append(spa);
					sb.append(cmwaProductMarketLaunchVo.getLegal() == null ? "" : cmwaProductMarketLaunchVo.getLegal());
					sb.append(spa);
					sb.append(cmwaProductMarketLaunchVo.getWfsy() == null ? "0" : cmwaProductMarketLaunchVo.getWfsy());
					sb.append(spa);
					sb.append(cmwaProductMarketLaunchVo.getNudistribute() == null ? "0" : cmwaProductMarketLaunchVo.getNudistribute());
					sb.append(spa);
					sb.append(cmwaProductMarketLaunchVo.getWeekYield() == null ? "0" : cmwaProductMarketLaunchVo.getWeekYield());
					sb.append(spa);
					bufferedWriter.write(sb.toString());
					bufferedWriter.write("\n");
				}
			}

			bufferedWriter.write("BTATOGZEND");
			bufferedWriter.write("\n");
			bufferedWriter.flush();
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				bufferedWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			try {
				fileWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return tempFile;
	}



}
